package com.cxf.windex.base.rest;

import com.cxf.windex.base.biz.BaseBiz;
import com.cxf.windex.base.msg.ObjectRestResponse;
import com.cxf.windex.base.secruity.JwtTokenUtil;
import com.cxf.windex.base.secruity.JwtUser;
import com.cxf.windex.base.secruity.JwtUserFactory;
import com.cxf.windex.base.util.FileFilterTool;
import com.cxf.windex.base.util.MapCache;
import com.cxf.windex.entity.CxfUser;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * ${DESCRIPTION}
 *
 * @author wanghaobin
 * @create 2017-06-15 8:48
 */
public class BaseRestController<Biz extends BaseBiz,Entity> {
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected Biz baseBiz;



    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    public static final Logger logger = LoggerFactory.getLogger(BaseRestController.class);

    /**
     * 文件存放 路径
     */
    @Value("${upload.path}")
    private String uploadPath;

    /**
     * 文件访问路径
     */
    @Value("${upload.url}")
    private String uploadUrl;

    protected MapCache cache = MapCache.single();

    protected Map<String, Object> resultMap = new HashMap<String, Object>();

    public BaseRestController title(  String title) {
        request.setAttribute("title", title);
        return this;
    }

    public BaseRestController keywords(  String keywords) {
        request.setAttribute("keywords", keywords);
        return this;
    }

    @RequestMapping(value = "",method = RequestMethod.POST)
    @ResponseBody
    public ObjectRestResponse<Entity> add(Entity entity){
        baseBiz.insertSelective(entity);
        return new ObjectRestResponse<Entity>().rel(true);
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<Entity> get(@PathVariable String id){
        return new ObjectRestResponse<Entity>().rel(true).result(baseBiz.selectById(id));
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    @ResponseBody
    public ObjectRestResponse<Entity> update(Entity entity){
        baseBiz.updateSelectiveById(entity);
        return new ObjectRestResponse<Entity>().rel(true);
    }
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public ObjectRestResponse<Entity> remove(@PathVariable Long id){
        baseBiz.deleteById(id);
        return new ObjectRestResponse<Entity>().rel(true);
    }

    @RequestMapping(value = "/all",method = RequestMethod.GET)
    @ResponseBody
    public List<Entity> list(){
        return baseBiz.selectListAll();
    }





    public void   updateCurrentUserName(CxfUser user){
        SecurityContext sc = SecurityContextHolder.getContext();
        if (sc.getAuthentication() == null) {
            return ;
        }
        Object principal = sc.getAuthentication().getDetails();
        if (principal instanceof JwtUser) {
            JwtUser oldUser = (JwtUser) principal;
            if(StringUtils.isNotBlank(user.getName())){
                oldUser.setName(user.getName());
            }
            if(StringUtils.isNotBlank(user.getType())){
                oldUser.setTypeId(user.getType());
            }
        }
    }

    public String setCurrentUserName(CxfUser user){
        JwtUser userDetails= JwtUserFactory.create(user);

        String token= jwtTokenUtil.generateToken(userDetails);
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), userDetails.getAuthorities()); // 进行安全认证
        upToken.setDetails(userDetails);
        SecurityContextHolder.getContext().setAuthentication(upToken);
        return token;
    }

    public String getCurrentUserType() {

        SecurityContext sc = SecurityContextHolder.getContext();
        if (sc.getAuthentication() == null) {
            return "0";
        }
        Object principal = sc.getAuthentication().getDetails();
        if (principal instanceof JwtUser) {
            JwtUser user = (JwtUser) principal;
            return user.getTypeId();
        }
        return "0";
    }

  public String getCurrentName() {
    SecurityContext sc = SecurityContextHolder.getContext();
    if (sc.getAuthentication() == null) {
      return "";
    }
    Object principal = sc.getAuthentication().getDetails();
    if (principal instanceof JwtUser) {
      JwtUser user = (JwtUser) principal;
      return user.getName();
    }
    return "";
  }

    public String getCurrentUserName(){
        String authorization = request.getHeader("to-Authorization");
        if(authorization==null || StringUtils.isBlank(authorization)){
            SecurityContext sc = SecurityContextHolder.getContext();
            if(sc.getAuthentication()==null){
                return "";
            }
            Object principal = sc.getAuthentication().getDetails();
            if (principal instanceof JwtUser) {
                JwtUser user = (JwtUser) principal;
                return user.getUsername();
            }
        }
        return jwtTokenUtil.getUsernameFromToken(authorization);
    }

    public String getCurrentVipStatus() {
        SecurityContext sc = SecurityContextHolder.getContext();
        if (sc.getAuthentication() == null) {
            return "0";
        }
        Object principal = sc.getAuthentication().getDetails();
        if (principal instanceof JwtUser) {
            JwtUser user = (JwtUser) principal;
            return user.getVipStatus();
        }
        return "0";
    }

    public String getCurrentUserId(){
        String authorization = request.getHeader("to-Authorization");
        if(authorization==null || StringUtils.isBlank(authorization)){
            SecurityContext sc = SecurityContextHolder.getContext();
            if(sc.getAuthentication()==null){
                return "";
            }
            Object principal = sc.getAuthentication().getDetails();
            if (principal instanceof JwtUser) {
                JwtUser user = (JwtUser) principal;
                return user.getId();
            }
        }
        return jwtTokenUtil.getUseridFromToken(authorization);
    }


    /**
     * 保存图片 返回Map
     * @param request
     * @param file 文件
     * @param type 文件类型
     * @return
     *   null 异常不处理
     *   -1  图片格式异常
     *   -2 图片保存异常
     *
     */
    public Map<String,String> saveFile(HttpServletRequest request,MultipartFile file,String type){
        if (file.isEmpty()) {
            return null;
        }
        FileFilterTool fileFilterTool=new FileFilterTool();
        if(!fileFilterTool.accept(file.getOriginalFilename())){
            return resultMap("-1","图片格式不正确。只能上传JPG,JPEG,GIF,PNG图片！");
        }
        try {
            String uuid= UUID.randomUUID().toString();
            String webRoot  = uploadPath  + File.separator  +type + File.separator+uuid+ File.separator;
            String saveUrl = uploadUrl+ "/" +type+ "/"+uuid+ "/"+ file.getOriginalFilename();

            File directoryFile = new File(webRoot);
            if(!directoryFile.exists()) {
                directoryFile.mkdirs();
            }
            logger.info("save path:"+webRoot);
            Path path = Paths.get(webRoot + file.getOriginalFilename());
            Files.write(path,  file.getBytes());
            Map<String, String> map = new HashMap<String, String>();
            map.put("filename",file.getOriginalFilename());
            map.put("saveUrl",saveUrl);
            map.put("code","0");
            logger.info("BankConfigController#saveFile processing : map= {},saveUrl={}", map,map.get("saveUrl"));
            return map;
        } catch (IOException e) {
            logger.error("BankConfigController#saveFile failed : IOException= {}", e);
            return resultMap("-2","图片保存异常！");
        }

    }

    /**
     * 返回结果信息
     *
     * @param code 0成功 -1失败
     * @param message 结算信息
     */
    public Map<String, String> resultMap(String code, String message) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("code", code);
        map.put("msg", message);
        return map;
    }
}
